<?php
namespace app\admin\controller;

use app\common\service\UserPermission as UserPermissionService;
use app\common\controller\Base;
use think\image\Exception;
use think\Request;
use think\Exception\HttpResponseException;

class Permission extends Base{

    /**
     * 权限列表
     */
    public function index(){

        $userPermissionService = new UserPermissionService();
        $permissions = $userPermissionService -> getPermissions();
        $page = $permissions->render();

        return view('',['permissions'=>$permissions,'page'=>$page]);
    }

    /**
     * @return \think\response\View
     */
    public function add(){
        return view();
    }

    /**
     * @param Request $request
     * @return array
     */
    public function create(Request $request){

        if(!$request->isPost()){
            $this->error("非法途径访问");
        }
        $data = $request -> only(['name','mark','group','status']);

        if(isset($data['status']) && $data['status'] == 'on'){
            $data['status'] = 1;
        }else{
            $data['status'] = 0;
        }

        $userPermissionService = new UserPermissionService();
        $result = $userPermissionService ->insert($data);

        if($result['state']) {
            $this->success("操作成功");
        }else{
            $this->error($result['message']);
        }
    }


    public function edit(Request $request){

        $input = $request->only(['id']);

        $id = intval($input['id']);

        if(!$id){
            $this->error("访问来源非法");
        }

        $userPermissionService = new UserPermissionService();
        $permission = $userPermissionService -> find($id);


        return view('',['permission'=>$permission]);
    }

    public function update(Request $request)
    {

        if (!$request->isPost()) {
            $this->error("非法访问途径");
        }

        $data = $request->only(['id','name','mark','group','status']);

        if(isset($data['status']) && $data['status'] == 'on'){
            $data['status'] = 1;
        }else{
            $data['status'] = 0;
        }

        $userPermissionService = new UserPermissionService();

        $result = $userPermissionService->update($data);

        if(1 == $result['state']){
            $this->success("更新成功");
        }
        $this->error("更新失败");
    }


    /**
     * @param Request $request
     * @return array
     */
    public function delete(Request $request){

        if(!$request->isDelete()){
            $this->error("非法访问途径");
        }

        $id = $request->only(['id']);
        if(count($id) !== 1){
            $this->error("禁止批量操作");
        }
        $userPermissionService = new UserPermissionService();

        $count = $userPermissionService -> delete($id);

        if($count){
            $this->success("操作成功");
        }else{
            $this->error("操作失败");
        }
    }


}